package com.example.pipline.yu.normal;

import com.example.pipline.yu.normal.step.PipelineStep;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.ArrayList;
import java.util.List;

// 管道执行器：管理事务和步骤执行
public class TransactionalPipeline {
    private final List<PipelineStep> steps = new ArrayList<>();
    private final PlatformTransactionManager transactionManager;

    public TransactionalPipeline(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    // 添加步骤
    public TransactionalPipeline addStep(PipelineStep step) {
        steps.add(step);
        return this;
    }

    // 执行管道，所有步骤在同一事务中
    public void execute(PipelineContext context) {
        // 定义事务属性
        DefaultTransactionDefinition txDefinition = new DefaultTransactionDefinition();
        txDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        // 开始事务
        TransactionStatus txStatus = transactionManager.getTransaction(txDefinition);

        try {
            // 依次执行所有步骤
            for (PipelineStep step : steps) {
                if (context.hasError()) {
                    break; // 若已有错误，终止流程
                }
                step.execute(context);
            }

            // 无错误则提交事务
            if (!context.hasError()) {
                transactionManager.commit(txStatus);
            } else {
                // 有错误则回滚
                transactionManager.rollback(txStatus);
            }
        } catch (Exception e) {
            // 异常发生时回滚
            transactionManager.rollback(txStatus);
            context.setError("管道执行失败: " + e.getMessage());
            throw new RuntimeException("管道执行异常", e);
        }
    }
}